package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @PackageName: com.itheima.controller
 * @ClassName: MemberController
 * @Description: TODO
 * @Author: ZDY
 * @DateTime: 2020/11/2 11:23
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;
    @RequestMapping("/backgroundAdd")
    public Result backgroundAdd(@RequestBody Member member, Integer healthManagerId){
        try {
            Date birthday = member.getBirthday();
            Calendar cal = Calendar.getInstance();
            if (cal.before(birthday)) { //出生日期晚于当前时间，无法计算
                return new Result(false , "输入的生日有误，请输入正确时间");
            }
            Member byTelephone = memberService.findByTelephone(member.getPhoneNumber());
            if (byTelephone == null) {
                memberService.backgroundAdd(member, healthManagerId);
            }else {
                return new Result(false , MessageConstant.ADD_MEMBER_FAIL);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.ADD_MEMBER_FAIL);
        }
        return new Result(true , MessageConstant.ADD_MEMBER_SUCCESS);
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return memberService.findPage(queryPageBean);
    }

    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            memberService.delete(id);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.DELETE_MEMBER_FAIL);
        }
        return new Result(true , MessageConstant.DELETE_MEMBER_SUCCESS);
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Member data = memberService.findById(id);
            return new Result(true , MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,data);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member){
        try {
            memberService.edit(member);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.EDIT_MEMBER_FAIL);
        }
        return new Result(true , MessageConstant.EDIT_MEMBER_SUCCESS);
    }

    /**
     * 根据勾选的id导出表
     * @param memberIds
     * @return
     */
    @RequestMapping("/exportMemberReport")
    public Result exportMemberReport(HttpServletRequest request, Integer[] memberIds, HttpServletResponse response){
        try {
            List<Map> list = memberService.exportMemberReport(memberIds);
//            return new Result(true , MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,member);

            //获得Excel模板文件绝对路径
            String temlateRealPath = request.getSession().getServletContext().getRealPath("template") +
                    File.separator + "member_template.xlsx";

            //读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));
            XSSFSheet sheet = workbook.getSheetAt(0);

            for (int i = 0; i < list.size(); i++) {
                sheet.createRow(1 + i);
                XSSFRow row = sheet.getRow(1 + i);
                Map map = list.get(i);
                String fileNumber = (String) map.get("fileNumber");
                String name = (String) map.get("name");
                String sex = (String) map.get("sex");
                String phoneNumber = (String) map.get("phoneNumber");
                String setmealNames = (String) map.get("setmealNames");
                String checkGroupNames = (String) map.get("checkGroupNames");
                String checkItemNames = (String) map.get("checkItemNames");
                for (int j = 0; j < 7; j++) {
                    row.createCell(j);
                }
                row.getCell(0).setCellValue(fileNumber);
                row.getCell(1).setCellValue(name);
                row.getCell(2).setCellValue(sex);
                row.getCell(3).setCellValue(phoneNumber);
                row.getCell(4).setCellValue(setmealNames);
                row.getCell(5).setCellValue(checkGroupNames);
                row.getCell(6).setCellValue(checkItemNames);
            }

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");// 告诉浏览器响应的内容的类型
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");// 告诉浏览器必须下载
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }

    }
}
